from django import template
from django.template.loader import render_to_string
from django.contrib.contenttypes.models import ContentType 
from ..models import UserImage

register = template.Library()


class RenderAlbumNode(template.Node):

    def __init__(self, objname):
        self.objname = objname

    def render(self, context):
        obj = context[self.objname]

        obj_type = ContentType.objects.get_for_model(obj)
        imglist = UserImage.objects.filter(content_type_id=obj_type.id, object_id=obj.id)
        return render_to_string("image/album.html", {"imglist":imglist}, context) 


def do_render_album(parser, token):
    """
    Syntax:: {% render_album for [object] %}
    """
    tokens = token.contents.split()
    if tokens[1] != 'for':
        raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])

    if len(tokens) != 3:
        raise template.TemplateSyntaxError("%s require to argument" % tokens[0])

    return RenderAlbumNode(tokens[2])    


register.tag('render_album', do_render_album)

